package com.ggh.jinjilive.ui.create;

import android.Manifest;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;

import androidx.annotation.Nullable;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.blankj.utilcode.util.BarUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.PermissionUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.ggh.jinjilive.BaseApplication;
import com.ggh.jinjilive.R;
import com.ggh.jinjilive.common.Constants;
import com.ggh.jinjilive.databinding.ActivityCreateListBinding;
import com.ggh.jinjilive.dialog.ChooseRoomDialog;
import com.ggh.jinjilive.dialog.CreateChannelDialog;
import com.ggh.jinjilive.listener.AddItemOnClickListener;
import com.ggh.jinjilive.listener.AddItemOnClickListener1;
import com.ggh.jinjilive.mobile.create.ChooseRoom;
import com.ggh.jinjilive.mobile.create.StartLiveMobile;
import com.ggh.jinjilive.mobile.home.live.LiveCategory;
import com.ggh.jinjilive.ui.BaseActivity;
import com.ggh.jinjilive.utils.ARouterUtils;
import com.ggh.jinjilive.utils.GlideEngine;
import com.bumptech.glide.Glide;
import com.ggh.jinjilive.utils.loginIMUtils;
import com.ggh.jinjilive.views.live.pk.commondef.LoginInfo;
import com.ggh.jinjilive.views.live.pk.http.HttpRequests;
import com.ggh.jinjilive.views.live.pk.http.HttpResponse;
import com.ggh.jinjilive.views.live.pk.http.PKHttpRequests;
import com.gyf.immersionbar.ImmersionBar;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.XXPermissions;
import com.huantansheng.easyphotos.EasyPhotos;
import com.huantansheng.easyphotos.callback.SelectCallback;
import com.huantansheng.easyphotos.models.album.entity.Photo;
import com.opensource.svgaplayer.SVGADrawable;
import com.opensource.svgaplayer.SVGAParser;
import com.opensource.svgaplayer.SVGAVideoEntity;

import org.jetbrains.annotations.NotNull;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

@Route(path = ARouterUtils.CreateLiveActivity)
public class CreateLiveActivity extends BaseActivity<ActivityCreateListBinding> implements View.OnClickListener{
    private CreateLiveViewModel createLiveViewModel;
    //选择类型
    private CreateChannelDialog createChannelDialog;
    //选择房间
    private ChooseRoomDialog chooseRoomDialog;
    //房间集合
    private List<ChooseRoom> chooseRoomList = new ArrayList<>();
    //
    private PKHttpRequests pkHttpRequests;
    @Override
    public void initCreate() {
        super.initCreate();
        ImmersionBar.with(this).statusBarDarkFont(false).navigationBarColor(R.color.white).navigationBarDarkIcon(true).init();
        BaseApplication.getInstance().getAppComponent().doInjectionMain(this);
        createLiveViewModel = new ViewModelProvider(this,viewModelFactory).get(CreateLiveViewModel.class);
    }

    @Override
    public int initContentView(Bundle savedInstanceState) {
        return R.layout.activity_create_list;
    }

    @Override
    public void initView() {
        super.initView();
        pkHttpRequests = new PKHttpRequests();
        //获取状态栏高度
        binding.llSpacing.setPadding(0, BarUtils.getStatusBarHeight(),0,0);
        //选择类型
        createChannelDialog = new CreateChannelDialog(mContext);
        //选择房间
        chooseRoomDialog = new ChooseRoomDialog(mContext);
        //直播间类目列表
        createLiveViewModel.liveCateGory();
    }

    @Override
    public void initData() {
        super.initData();
        //头像
        Glide.with(binding.RoundedImageView.getContext()).load(userMobile.getHead_portrait()).into(binding.RoundedImageView);
        //直播间头像
        Glide.with(binding.RoundedImageView1.getContext()).load(userMobile.getHead_portrait()).into(binding.RoundedImageView1);
        //封面
        createLiveViewModel.stringObservableField.set(userMobile.getHead_portrait());
        //直播间名称
        binding.streamerName.setText(userMobile.getNickname());
        //位置
        binding.tvCreateLocation.setText(userMobile.getCity());
        //选择房间
        chooseRoomList.clear();
        ChooseRoom chooseRoom = new ChooseRoom();
        chooseRoom.setID(0);
        chooseRoom.setRoomName("普通房");
        chooseRoom.setRoomPicture(R.mipmap.normal_room_icon2);
        chooseRoomList.add(chooseRoom);
        ChooseRoom chooseRoom1 = new ChooseRoom();
        chooseRoom1.setID(1);
        chooseRoom1.setRoomName("计时房");
        chooseRoom1.setRoomPicture(R.mipmap.time_limited_room_icon1);
        chooseRoomList.add(chooseRoom1);
        ChooseRoom chooseRoom2 = new ChooseRoom();
        chooseRoom2.setID(2);
        chooseRoom2.setRoomName("付费房");
        chooseRoom2.setRoomPicture(R.mipmap.diamond_required_room_icon1);
        chooseRoomList.add(chooseRoom2);
        ChooseRoom chooseRoom3 = new ChooseRoom();
        chooseRoom3.setID(3);
        chooseRoom3.setRoomName("密码房");
        chooseRoom3.setRoomPicture(R.mipmap.password_required_room_icon1);
        chooseRoomList.add(chooseRoom3);
        createLiveViewModel.chooseRoomLiveData.set(chooseRoomList);
        //默认选择
        createLiveViewModel.chooseRoomObservableField.set(chooseRoom);
        binding.tvChooseRoom.setText(chooseRoom.getRoomName());
        //开始直播
        createLiveViewModel.StartLiveMobileMutableLiveData.observe(this, new Observer<StartLiveMobile>() {
            @Override
            public void onChanged(StartLiveMobile startLiveMobile) {
                //添加推流
                pkHttpRequests.addPusher(startLiveMobile.getRoom_id(), userMobile.getUser_id(), userMobile.getNickname(), userMobile.getHead_portrait(), startLiveMobile.getPush_url(), new PKHttpRequests.OnResponseCallback<HttpResponse>() {
                    @Override
                    public void onResponse(int retcode, @Nullable @org.jetbrains.annotations.Nullable String retmsg, @Nullable @org.jetbrains.annotations.Nullable HttpResponse data) {
                        LogUtils.d("添加成功" + retmsg);
                    }
                });
                //创建群
                loginIMUtils.createGroup(startLiveMobile.getRoom_id(),createLiveViewModel.titleObservableField.get());
                //跳转到直播间
                ARouter.getInstance().build(ARouterUtils.TVLiveActivity).withSerializable("startLiveMobile",startLiveMobile).navigation();
                finish();
            }
        });

        LoginInfo loginInfo = new LoginInfo();
        loginInfo.sdkAppID = Constants.SDKAppID;
        loginInfo.userID = userMobile.getUser_id();
        loginInfo.userSig = loginIMUtils.genTestUserSig(userMobile.getUser_id());
        loginInfo.userName = userMobile.getNickname();
        loginInfo.userAvatar = userMobile.getHead_portrait();
        HttpRequests.getInstance().login(loginInfo);
    }

    /**
     * 选择房间数据
     */
    public void chooseRoomData(){
        //选择房间
        chooseRoomList.clear();
        ChooseRoom chooseRoom = new ChooseRoom();
        chooseRoom.setID(0);
        chooseRoom.setRoomName("普通房");
        chooseRoom.setRoomPicture(R.mipmap.normal_room_icon1);
        chooseRoomList.add(chooseRoom);
        ChooseRoom chooseRoom1 = new ChooseRoom();
        chooseRoom1.setID(1);
        chooseRoom1.setRoomName("计时房");
        chooseRoom1.setRoomPicture(R.mipmap.time_limited_room_icon1);
        chooseRoomList.add(chooseRoom1);
        ChooseRoom chooseRoom2 = new ChooseRoom();
        chooseRoom2.setID(2);
        chooseRoom2.setRoomName("付费房");
        chooseRoom2.setRoomPicture(R.mipmap.diamond_required_room_icon1);
        chooseRoomList.add(chooseRoom2);
        ChooseRoom chooseRoom3 = new ChooseRoom();
        chooseRoom3.setID(3);
        chooseRoom3.setRoomName("密码房");
        chooseRoom3.setRoomPicture(R.mipmap.password_required_room_icon1);
        chooseRoomList.add(chooseRoom3);
        createLiveViewModel.chooseRoomLiveData.set(chooseRoomList);
    }

    @Override
    public void initViewObservable() {
        super.initViewObservable();
        //更换头像
        binding.RoundedImageView1.setOnClickListener(this);
        //选择类型
        binding.tvChooseType.setOnClickListener(this);
        //选择房间
        binding.tvChooseRoom.setOnClickListener(this);
        //关闭
        binding.llCreateOcclude.setOnClickListener(this);
        //开始直播
        binding.startLive.setOnClickListener(this);

        //
        binding.startCs.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                try { // new URL needs try catch.
                    SVGAParser parser = SVGAParser.Companion.shareParser();
                    parser.decodeFromURL(new URL("http://live.hefeiboge.cn/uploads/20210512/c41b053a7fbafac8036ea83a89fec203.svga"), new SVGAParser.ParseCompletion() {
                        @Override
                        public void onComplete(@NotNull SVGAVideoEntity videoItem) {
                            SVGADrawable drawable = new SVGADrawable(videoItem);
                            binding.liveSvg.setImageDrawable(drawable);
                            binding.liveSvg.startAnimation();
                        }
                        @Override
                        public void onError() {

                        }
                    });
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.ll_create_occlude://关闭当前
                finish();
                break;
            case R.id.tv_choose_type://选择类型
                if(null != createLiveViewModel.listMutableLiveData && createLiveViewModel.listMutableLiveData.get().size() > 0){
                    if(null != createChannelDialog && !createChannelDialog.isShowing()){
                        createChannelDialog.show();
                        createChannelDialog.setLiveCategory(createLiveViewModel.listMutableLiveData.get(),createLiveViewModel.liveCategoryObservableField.get());
                        createChannelDialog.setAddItemOnClickListener(new AddItemOnClickListener() {
                            @Override
                            public void onSkipClicked(int position, Object mObject) {
                                LiveCategory liveCategory = (LiveCategory) mObject;
                                if(null != liveCategory){
                                    createChannelDialog.dismiss();
                                    createLiveViewModel.liveCategoryObservableField.set(liveCategory);
                                    binding.tvChooseType.setText(liveCategory.getCategory_name());
                                }
                            }
                        });
                    }
                }
                break;
            case R.id.RoundedImageView1://直播间头像
                EasyPhotos.createAlbum(this, true,false, GlideEngine.getInstance())//参数说明：上下文，是否显示相机按钮，是否使用宽高数据（false时宽高数据为0，扫描速度更快），[配置Glide为图片加载引擎](https://github.com/HuanTanSheng/EasyPhotos/wiki/12-%E9%85%8D%E7%BD%AEImageEngine%EF%BC%8C%E6%94%AF%E6%8C%81%E6%89%80%E6%9C%89%E5%9B%BE%E7%89%87%E5%8A%A0%E8%BD%BD%E5%BA%93)
                        .setFileProviderAuthority("com.ggh.jinjilive.fileprovider")//参数说明：见下方`FileProvider的配置`
                        .start(new SelectCallback() {
                            @Override
                            public void onResult(ArrayList<Photo> photos, boolean isOriginal) {
                                if(photos.size() > 0){
                                    createLiveViewModel.photoObservableField.set(photos.get(0));
                                    Glide.with(binding.RoundedImageView1.getContext()).load(photos.get(0).path).into(binding.RoundedImageView1);
                                    createLiveViewModel.isRefresh = true;
                                }
                            }

                            @Override
                            public void onCancel() {

                            }
                        });
                break;
            case R.id.tv_choose_room://选择房间类型
                if(null != chooseRoomDialog && !chooseRoomDialog.isShowing()){
                    chooseRoomDialog.show();
                    chooseRoomDialog.setTEXT();
                    chooseRoomDialog.setLiveCategory(createLiveViewModel.chooseRoomLiveData.get(),createLiveViewModel.chooseRoomObservableField.get());
                    chooseRoomDialog.setAddItemOnClickListener(new AddItemOnClickListener1() {
                        @Override
                        public void onSkipClicked(int position, Object mObject, String magnitude) {
                            chooseRoomDialog.dismiss();
                            ChooseRoom chooseRoom = (ChooseRoom) mObject;
                            if(null != chooseRoom){
                                chooseRoomData();
                                if(position == 0){
                                    createLiveViewModel.chooseRoomLiveData.get().get(position).setRoomPicture(R.mipmap.normal_room_icon2);
                                }else if(position == 1){
                                    createLiveViewModel.chooseRoomLiveData.get().get(position).setRoomPicture(R.mipmap.time_limited_room_icon2);
                                    //每分钟扣费金额 type=3时，必须存在
                                    createLiveViewModel.price_minObservableField.set(magnitude);
                                    //付费金额 type=2时，必须存在
                                    createLiveViewModel.priceObservableField.set("");
                                    //密码
                                    createLiveViewModel.passwordObservableField.set("");

                                }else if(position == 2){
                                    createLiveViewModel.chooseRoomLiveData.get().get(position).setRoomPicture(R.mipmap.diamond_required_room_icon2);
                                    //每分钟扣费金额 type=3时，必须存在
                                    createLiveViewModel.price_minObservableField.set("");
                                    //付费金额 type=2时，必须存在
                                    createLiveViewModel.priceObservableField.set(magnitude);
                                    //密码
                                    createLiveViewModel.passwordObservableField.set("");
                                }else if(position == 3){
                                    createLiveViewModel.chooseRoomLiveData.get().get(position).setRoomPicture(R.mipmap.password_required_room_icon2);
                                    //每分钟扣费金额 type=3时，必须存在
                                    createLiveViewModel.price_minObservableField.set("");
                                    //付费金额 type=2时，必须存在
                                    createLiveViewModel.priceObservableField.set("");
                                    //密码
                                    createLiveViewModel.passwordObservableField.set(magnitude);
                                }
                                createLiveViewModel.chooseRoomObservableField.set(chooseRoom);
                                binding.tvChooseRoom.setText(chooseRoom.getRoomName());
                            }
                        }
                    });
                }
                break;
            case R.id.start_live://开始直播
                if(userMobile.getIs_anchor_auth() != 1){
                    ToastUtils.make().show("您还没有成为主播哦");
                    return;
                }
                if(TextUtils.isEmpty(binding.etTitle.getText().toString())){
                    ToastUtils.make().show("请输入直播标题");
                    return;
                }
                createLiveViewModel.titleObservableField.set(binding.etTitle.getText().toString());

                boolean successful = PermissionUtils.isGranted(Manifest.permission.CAMERA,
                        Manifest.permission.RECORD_AUDIO);
                if(!successful){
                    XXPermissions.with(this).permission(Manifest.permission.CAMERA,
                            Manifest.permission.RECORD_AUDIO).request(new OnPermissionCallback() {
                        @Override
                        public void onGranted(List<String> permissions, boolean all) {
                            if (all) {
                                ToastUtils.make().show("权限获取成功");
                                //判断是否更换过图片
                                if(createLiveViewModel.isRefresh){
                                    createLiveViewModel.uploadimages();
                                }else {
                                    createLiveViewModel.openLive();
                                }
                            } else {
                                ToastUtils.make().show("权限获取失败");
                            }
                        }
                    });
                }else {
                    //判断是否更换过图片
                    if(createLiveViewModel.isRefresh){
                        createLiveViewModel.uploadimages();
                    }else {
                        createLiveViewModel.openLive();
                    }
                }
                break;
        }
    }
}
